package com.fansea.util;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
 
public class DownloadFile {
    public static String saveImg(String fileUrl) {
//        String fileUrl = ; // 替换为你要下载的文件URL
        String localPath = "E:\\wximg\\girl\\"+System.currentTimeMillis()+".jpeg"; // 本地文件保存路径
 
        try {
            URL url = new URL(fileUrl);
            URLConnection connection = url.openConnection();
            InputStream inputStream = connection.getInputStream();
            FileOutputStream outputStream = new FileOutputStream(localPath);
 
            byte[] buffer = new byte[1024];
            int bytesRead;
 
            // 将InputStream的内容读到OutputStream
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
 
            // 关闭流
            inputStream.close();
            outputStream.close();
            return localPath;
//            System.out.println("文件下载成功，保存在: " + localPath);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("文件下载失败: " + e.getMessage());
            return fileUrl;
        }
    }

    public static void main(String[] args) {
        saveImg("https://s0.wp.com/mshots/v1/https://www.baidu.com/?w=600&h=400");
    }
}